<?php


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @method static create(array $data)
 * @method static where(array $data)
 */
class BaseModel extends Model
{

    # 隐藏字段信息
    ## 比如我的密码不能够在查询的时候显示出来, 以及删除字段deleted_at
    protected $hidden = ['deleted_at', 'password'];

    #   时间格式取出来之后转化为时间戳格式
    #   方法名称应与被转换字段名称相同
    protected function getCreatedAtAttribute()
    {
        return strtotime($this->attributes['created_at']);
    }

    protected function getUpdatedAtAttribute()
    {
        return strtotime($this->attributes['updated_at']);
    }

    /**
     * 快速查找一条数据
     * 查询不到返回NULL
     * @param $where array  条件
     * @param $field array  字段
     * @return mixed
     */
    public function getOne(array $where, array $field = [])
    {
        $obj = self::getObj($where, $field);
        return $obj->first();
    }

    /**
     * @param false $size 默认false, 不分页, 具体值, 表示分页条数
     * @param array $where 条件
     * @param array $field 字段
     * @param array $order demo ['created_at'=>'asc','id'=>'desc'] 先按时间升序, 如果时间相同, 再按id降序
     * @param array $whereIn ['id',[3,4,5]]  id 在数组[3,4,5]
     * @return mixed  数据不存在,返回[]
     */
    public function getMany($size = False, array $where = [], $field = [], $order = [], $whereIn = [])
    {
        $obj = self::getObj($where, $field, $order, $whereIn);
        return $size == false ? $obj->get() : page($obj->paginate($size));
    }

    public function getAllData($where = [], $field = [], $order = [], $whereIn = [])
    {
        $obj = self::getObj($where, $field, $order, $whereIn);
        return $obj->get();
    }

    protected function getObj($where = [], $field = [], $order = [], $whereIn = [])
    {
        $obj = self::when($field, function ($query) use ($field) {
            return $query->select($field);
        })->when($where, function ($query) use ($where) {
            return $query->where($where);
        })->when($order, function ($query) use ($order) {
            foreach ($order as $k => $v) {
                $query->orderBy($k, $v);
            }
            return $query;
        })->when($whereIn, function ($query) use ($whereIn) {
            return $query->whereIn($whereIn[0], $whereIn[1]);
        });
        return $obj;
    }
}
